﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using PCR.Base;
using PCR.Logic;

using System.Collections;
using System.Runtime.InteropServices;

namespace PCR
{
    //public partial class UserCheckReport : Form
    public partial class UserCheckReport : DevComponents.DotNetBar.Office2007Form
    {
        string _strChoseSign = "√";
        IPatientManager _patientManager = null;
        public UserCheckReport()
        {
            InitializeComponent();

            _patientManager = PCRRoot.Instance.PatientManager;

            this.tbAgeFrom.Text = "0";
            this.tbAgeTo.Text = "100";
            this.cbGender.SelectedIndex = 0;

            IVirusTypeManager virusTypeMgr = PCRRoot.Instance.VirusTypeManager;
            if(virusTypeMgr != null)
            {
                foreach (IVirusType type in virusTypeMgr.List)
                {
                    this.dataGridView1.Rows.Add(false, type.Name, 1, 100);
                }
            }

            foreach(ColumnHeader col in ltvReports.Columns)
            {
                tsmiToShow.DropDownItems.Add(_strChoseSign + col.Text);
            }
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            UInt32 uiAgeFrom = 0; 
            bool bAge = UInt32.TryParse(this.tbAgeFrom.Text, out uiAgeFrom);
            if (!bAge || uiAgeFrom < 0)
            {
                MessageBox.Show("开始年龄输入有误!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.tbAgeFrom.Focus();
                return;
            }

            UInt32 uiAgeTo = 0;
            bAge = UInt32.TryParse(this.tbAgeTo.Text, out uiAgeTo);
            if (!bAge || uiAgeTo < uiAgeFrom)
            {
                MessageBox.Show("截至年龄输入有误!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.tbAgeTo.Focus();
                return;
            }

            IList<Gender> listGender = new List<Gender>();
            if (this.cbGender.Text != PCRRoot.GenderString(Gender.MAN) && this.cbGender.Text != PCRRoot.GenderString(Gender.WOMEN))
            {
                listGender.Add(Gender.MAN);
                listGender.Add(Gender.WOMEN);
            }
            else
            {
                listGender.Add(PCRRoot.GenderValue(this.cbGender.Text));
            }

            IList<Guid> listVirusType = new List<Guid>();
            int j = 0;
            foreach (DataGridViewRow row in this.dataGridView1.Rows)
            {
                j++; if (j == this.dataGridView1.Rows.Count || bool.Parse(row.Cells[0].Value.ToString())) continue;
                listVirusType.Add(PCRRoot.VirusTypeValue(row.Cells[1].Value.ToString()).ObjectID);
            }

            IList<IPatientReport> listResult = PCRRoot.SearchReport(this.textBox1.Text,
                DateTime.Parse(this.dtReportDateFrom.Text), DateTime.Parse(this.dtReportDateTo.Text),
                DateTime.Parse(this.dtCheckDateFrom.Text), DateTime.Parse(this.dtCheckDateTo.Text),
                uiAgeFrom, uiAgeTo, listGender, listVirusType);

            AddSearchResultToListView(listResult);
        }
        
        private void btnSearchAll_Click(object sender, EventArgs e)
        {
            IList<IPatientReport> listResult = PCRRoot.SearchAllReport();
            AddSearchResultToListView(listResult);
        }

        private void AddOneReportToListView(IPatientReport report)
        {
            ListViewItem item = new ListViewItem(report.ReportDate.ToShortDateString());
            item.Tag = report;
            item.SubItems.Add(report.ReportID);
            item.SubItems.Add(report.Name.ToString());
            item.SubItems.Add(report.Age.ToString());
            item.SubItems.Add(PCRRoot.GenderString(report.Gender));
            item.SubItems.Add(report.CheckDate.ToShortDateString());
            item.SubItems.Add(report.SampleID);
            item.SubItems.Add(report.SampleReceiveDate.ToShortDateString());
            item.SubItems.Add(PCRRoot.CheckMethodString(report.CheckMethod));
            item.SubItems.Add(PCRRoot.SampleTypeString(report.SampleType));
            item.SubItems.Add(PCRRoot.SampleStateString(report.SampleState));

            string strDanger = "";//PCRRoot.GetTypeHeader();
            string strExponent = "";
            int i = 0;
            foreach (IPatientVirus virus in report.PatientVirusList)
            {
                strDanger += PCRRoot.VirusTypeString(virus.VirusTypeID);
                strExponent += virus.Exponent.ToString();
                i++;
                if (i != report.PatientVirusList.Count)
                {
                    strDanger += PCRRoot.GetSpitterSign();
                    strExponent += PCRRoot.GetSpitterSign();
                }
            }
            item.SubItems.Add(strDanger);
            item.SubItems.Add(strExponent);
            item.SubItems.Add(report.CellPrinciple);
            item.SubItems.Add(report.PathologyPrinciple);
            ltvReports.Items.Add(item);
        }

        void AddSearchResultToListView(IList<IPatientReport> listResult)
        {
            this.ltvReports.Items.Clear();
            this.richTextBox1.ResetText();
            if (listResult == null || listResult.Count <= 0)
            {
                MessageBox.Show("没有查到结果!\n请重新设置查询条件", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            else
            {
                MessageBox.Show("共计查询到"+ listResult.Count.ToString() +"条记录!\n", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            
            foreach (IPatientReport report in listResult)
            {
                AddOneReportToListView(report);
            }
            
            this.ltvReports.Items[0].Selected = true;
            this.ltvReports.Items[0].Focused = true;
        }

        private void tsbAddReport_Click(object sender, EventArgs e)
        {
            FormUserReportInfo info = new FormUserReportInfo(true, null);
            if (DialogResult.OK == info.ShowDialog())
            {
                AddOneReportToListView(info._report);
            }
        }

        private void tsbDelReport_Click(object sender, EventArgs e)
        {
            DeleteSeletedItem();
        }

        private void DeleteSeletedItem()
        {
            if (this.ltvReports.SelectedIndices.Count == 0)
            {
                //MessageBox.Show("请选择一个样本", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            if (MessageBox.Show(string.Format("确定删除选择的病人信息么？"), "提示",
                MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
            {
                int i = this.ltvReports.SelectedItems.Count;
                for (int j = 0; j < i; j++)
                {
                    ListViewItem item = this.ltvReports.Items[this.ltvReports.SelectedIndices[0]];
                    IPatientReport report = item.Tag as IPatientReport;
                    if (report == null) continue;
                    PCRRoot.Instance.PatientManager.RemoveByID(report.ObjectID);
                    this.ltvReports.Items.RemoveAt(this.ltvReports.SelectedIndices[0]);
                }
                this.richTextBox1.ResetText();
            }
        }

        private void ModifySelectedItem()
        {
            if (this.ltvReports.SelectedIndices.Count == 0)
            {
                //MessageBox.Show("请选择一个样本", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            int selIndex = this.ltvReports.SelectedIndices[0];
            ListViewItem item = this.ltvReports.Items[selIndex];

            IPatientReport report = item.Tag as IPatientReport;
            if (report == null)
                return;

            FormUserReportInfo info = new FormUserReportInfo(false, report);
            if (DialogResult.OK == info.ShowDialog())
            {
                item.Tag = info._report;
                item.SubItems[0].Text = (info._report.ReportDate.ToShortDateString());
                item.SubItems[1].Text = (info._report.ReportID);
                item.SubItems[2].Text = (info._report.Name.ToString());
                item.SubItems[3].Text = (info._report.Age.ToString());
                item.SubItems[4].Text = (PCRRoot.GenderString(info._report.Gender));
                item.SubItems[5].Text = (info._report.CheckDate.ToShortDateString());
                item.SubItems[6].Text = (info._report.SampleID);
                item.SubItems[7].Text = (info._report.SampleReceiveDate.ToShortDateString());
                item.SubItems[8].Text = (PCRRoot.CheckMethodString(info._report.CheckMethod));
                item.SubItems[9].Text = (PCRRoot.SampleTypeString(info._report.SampleType));
                item.SubItems[10].Text = (PCRRoot.SampleStateString(info._report.SampleState));

                string strDanger = "";//PCRRoot.GetTypeHeader();
                string strExponent = "";
                int i = 0;
                foreach (IPatientVirus virus in info._report.PatientVirusList)
                {
                    strDanger += PCRRoot.VirusTypeString(virus.VirusTypeID);
                    strExponent += virus.Exponent.ToString();
                    i++;
                    if (i != info._report.PatientVirusList.Count)
                    {
                        strDanger += PCRRoot.GetSpitterSign();
                        strExponent += PCRRoot.GetSpitterSign();
                    }
                }
                item.SubItems[11].Text = (strDanger);
                item.SubItems[12].Text = (strExponent);
                item.SubItems[13].Text = (info._report.CellPrinciple);
                item.SubItems[14].Text = (info._report.PathologyPrinciple);
                ShowOneRowToHintBox();
            }
        }

        private void tsbModifyReport_Click(object sender, EventArgs e)
        {
            ModifySelectedItem();
        }

        private void ltvReports_DoubleClick(object sender, EventArgs e)
        {
            ModifySelectedItem();
        }

        void ShowOneRowToHintBox()
        {
            if (this.ltvReports.SelectedIndices.Count == 0)
            {
                return;
            }

            int selIndex = this.ltvReports.SelectedIndices[0];
            ListViewItem item = this.ltvReports.Items[selIndex];

            IPatientReport report = item.Tag as IPatientReport;
            if (report == null)
                return;

            //报告编号1，病人编号，姓名2，性别4，年龄3，HPV亚型11，感染单位12
            //this.richTextBox1.ResetText();
            //this.richTextBox1.Text = this.colNumber.Text;
            //this.richTextBox1.Text += ":\t";
            //this.richTextBox1.Text += item.SubItems[1].Text;
            //this.richTextBox1.Text += "\n";
            //this.richTextBox1.Text += this.colName.Text;
            //this.richTextBox1.Text += ":\t";
            //this.richTextBox1.Text += item.SubItems[2].Text;
            //this.richTextBox1.Text += "\n"; 
            //this.richTextBox1.Text += this.colAge.Text;
            //this.richTextBox1.Text += ":\t\t";
            //this.richTextBox1.Text += item.SubItems[3].Text;
            //this.richTextBox1.Text += "\n"; 
            //this.richTextBox1.Text += this.colGender.Text;
            //this.richTextBox1.Text += ":\t\t";
            //this.richTextBox1.Text += item.SubItems[4].Text;
            //this.richTextBox1.Text += "\n"; 
            //this.richTextBox1.Text += this.colHighDangerType.Text;
            //this.richTextBox1.Text += ":\t";
            //this.richTextBox1.Text += item.SubItems[11].Text;
            //this.richTextBox1.Text += "\n"; 
            //this.richTextBox1.Text += this.colInfectNumber.Text;
            //this.richTextBox1.Text += ":\t";
            //this.richTextBox1.Text += item.SubItems[12].Text;

            this.richTextBox1.ResetText();
            this.richTextBox1.Text = this.colNumber.Text;
            this.richTextBox1.Text += ":\t";
            this.richTextBox1.Text += report.ReportID;
            this.richTextBox1.Text += "\n";
            this.richTextBox1.Text += this.colName.Text;
            this.richTextBox1.Text += ":\t";
            this.richTextBox1.Text += report.Name;
            this.richTextBox1.Text += "\n";
            this.richTextBox1.Text += this.colAge.Text;
            this.richTextBox1.Text += ":\t\t";
            this.richTextBox1.Text += report.Age.ToString();
            this.richTextBox1.Text += "\n";
            this.richTextBox1.Text += this.colGender.Text;
            this.richTextBox1.Text += ":\t\t";
            this.richTextBox1.Text += PCRRoot.GenderString(report.Gender);
            this.richTextBox1.Text += "\n";

            IList<IPatientVirus> lowTypeList = new List<IPatientVirus>();
            IList<IPatientVirus> highTypeList = new List<IPatientVirus>();
            foreach (IPatientVirus virus in report.PatientVirusList)
            {
                IVirusType type = PCRRoot.Instance.VirusTypeManager.GetByID(virus.VirusTypeID);
                if (type == null) // Not existed
                    continue;

                if (type.VirusDefineType == VirusDefineType.LOWDANGER)
                {
                    lowTypeList.Add(virus);
                }

                if (type.VirusDefineType == VirusDefineType.HIGHDANGER)
                {
                    highTypeList.Add(virus);
                }
            }
            
            string strSplitter = "\t";
            string strSplitter2 = "[";
            string strSplitter3 = "]";
            if (lowTypeList.Count > 0)
            {
                this.richTextBox1.Text += "=====" + PCRRoot.VirusDefineTypeString(VirusDefineType.LOWDANGER) + "=====\n";
                this.richTextBox1.Text += this.colHighDangerType.Text + strSplitter + this.colInfectNumber.Text + "\n";
                
                foreach(IPatientVirus pVirus in lowTypeList)
                {
                    this.richTextBox1.Text += PCRRoot.Instance.VirusTypeManager.GetByID(pVirus.VirusTypeID).Name;
                    this.richTextBox1.Text += strSplitter + pVirus.Exponent.ToString();

                    this.richTextBox1.Text += strSplitter2;
                    string strRst = "";
                    PCRRoot.JudgeExponent(pVirus.Exponent, out strRst);
                    this.richTextBox1.Text += strRst;
                    this.richTextBox1.Text += strSplitter3;

                    this.richTextBox1.Text += "\n";
                }
            }

            if (highTypeList.Count > 0)
            {
                this.richTextBox1.Text += "=====" + PCRRoot.VirusDefineTypeString(VirusDefineType.HIGHDANGER) + "=====\n";
                this.richTextBox1.Text += this.colHighDangerType.Text + strSplitter + this.colInfectNumber.Text + "\n";

                foreach (IPatientVirus pVirus in highTypeList)
                {
                    this.richTextBox1.Text += PCRRoot.Instance.VirusTypeManager.GetByID(pVirus.VirusTypeID).Name;
                    this.richTextBox1.Text += strSplitter + pVirus.Exponent.ToString();

                    this.richTextBox1.Text += strSplitter2;
                    string strRst = "";
                    PCRRoot.JudgeExponent(pVirus.Exponent, out strRst);
                    this.richTextBox1.Text += strRst;
                    this.richTextBox1.Text += strSplitter3;

                    this.richTextBox1.Text += "\n";
                }
            }
        }

        private void ltvReports_SelectedIndexChanged(object sender, EventArgs e)
        {
            ShowOneRowToHintBox();
        }

        private void ModifyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ModifySelectedItem();
        }

        private void PrintToolStripMenuItem_Click(object sender, EventArgs e)
        {
            PrintSelectedItem();
        }

        private void DeleteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DeleteSeletedItem();
        }

        private void tsbExport_Click(object sender, EventArgs e)
        {
            ExportReportList();
        }

        private void tsbPrint_Click(object sender, EventArgs e)
        {
            PrintSelectedItem();
        }

        private void PrintSelectedItem()
        {
            // No item selected
            if (this.ltvReports.SelectedIndices.Count == 0)
                return ;

            // Get the patient report interface
            IPatientReport patientReport = this.ltvReports.SelectedItems[0].Tag as IPatientReport;
            System.Diagnostics.Debug.Assert(patientReport != null);
            
            // Show the printing dialog
            FormReportPrinting printForm = new FormReportPrinting(patientReport);
            
            // Just show it, we don't care the result
            printForm.ShowDialog();
        }

        private void ExportReportList()
        {
            if (this.ltvReports.SelectedIndices.Count == 0)
            {
                //MessageBox.Show("请选择一个样本", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            string saveFileName = "";
            SaveFileDialog saveDialog = new SaveFileDialog();
            saveDialog.DefaultExt = "xls";
            saveDialog.Filter = "Excel文件|*.xls";
            saveDialog.FileName = DateTime.Now.ToString("yyyy-MM-dd");
            if (DialogResult.OK != saveDialog.ShowDialog()) return;

            saveFileName = saveDialog.FileName;

            IList<IPatientReport> reports = new List<IPatientReport>();
            int i = this.ltvReports.SelectedItems.Count;
            for (int j = 0; j < i; j++)
            {
                ListViewItem item = this.ltvReports.Items[this.ltvReports.SelectedIndices[j]];
                IPatientReport report = item.Tag as IPatientReport;
                if (report == null) continue;
                reports.Add(report);
            }

            if (PCRRoot.Instance.IOManager.ExportToExcel(saveFileName, reports))
            {
                MessageBox.Show("导出成功！\n"+ saveFileName, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);                
            }
            else
            {
                MessageBox.Show("导出失败！\n" + saveFileName, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void tsmiExport_Click(object sender, EventArgs e)
        {
            ExportReportList();
        }

        private void tsmiToShow_DropDownItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            int idx = tsmiToShow.DropDownItems.IndexOf(e.ClickedItem);
            if (e.ClickedItem.Text.StartsWith(_strChoseSign))
            {
                //To Hidden
                e.ClickedItem.Text = e.ClickedItem.Text.Substring(_strChoseSign.Length);
                ltvReports.Columns[idx].Width = 0;
            }
            else
            {
                //To Show
                e.ClickedItem.Text =  _strChoseSign + e.ClickedItem.Text;
                ltvReports.Columns[idx].Width = 80;
            }
        }

        #region "ReportListSort"

        #region 自定义变量
        int currentCol = -1;
        bool sort;
        #endregion

        public class ListViewItemComparer : IComparer
        {
            public bool sort_b;
            public SortOrder order = SortOrder.Ascending;

            private int col;

            public ListViewItemComparer()
            {
                col = 0;
            }

            public ListViewItemComparer(int column, bool sort)
            {
                col = column;
                sort_b = sort;
            }

            public int Compare(object x, object y)
            {
                if (sort_b)
                {
                    return String.Compare(((ListViewItem)x).SubItems[col].Text, ((ListViewItem)y).SubItems[col].Text);
                }
                else
                {
                    return String.Compare(((ListViewItem)y).SubItems[col].Text, ((ListViewItem)x).SubItems[col].Text);
                }
            }
        }

        #endregion "ReportListSort"

        private void ltvReports_ColumnClick(object sender, ColumnClickEventArgs e)
        {
            if (ltvReports.Items.Count == 0)
            {
                return;
            }

            string Asc = ((char)0x25bc).ToString().PadLeft(4, ' ');
            string Des = ((char)0x25b2).ToString().PadLeft(4, ' ');

            if (sort == false)
            {
                sort = true;
                string oldStr = this.ltvReports.Columns[e.Column].Text.TrimEnd((char)0x25bc, (char)0x25b2, ' ');
                this.ltvReports.Columns[e.Column].Text = oldStr + Des;
            }
            else if (sort == true)
            {
                sort = false;
                string oldStr = this.ltvReports.Columns[e.Column].Text.TrimEnd((char)0x25bc, (char)0x25b2, ' ');
                this.ltvReports.Columns[e.Column].Text = oldStr + Asc;
            }

            ltvReports.ListViewItemSorter = new ListViewItemComparer(e.Column, sort);
            this.ltvReports.Sort();
            int rowCount = this.ltvReports.Items.Count;
            if (currentCol != -1)
            {
                for (int i = 0; i < rowCount; i++)
                {
                    this.ltvReports.Items[i].UseItemStyleForSubItems = false;
                    this.ltvReports.Items[i].SubItems[currentCol].BackColor = Color.White;

                    if (e.Column != currentCol)
                        this.ltvReports.Columns[currentCol].Text = this.ltvReports.Columns[currentCol].Text.TrimEnd((char)0x25bc, (char)0x25b2, ' ');
                }
            }

            for (int i = 0; i < rowCount; i++)
            {
                this.ltvReports.Items[i].UseItemStyleForSubItems = false;
                this.ltvReports.Items[i].SubItems[e.Column].BackColor = Color.WhiteSmoke;
                currentCol = e.Column;
            }
        }

        private void tsbSearch_Click(object sender, EventArgs e)
        {
            if (this.splitContainerEx2.Panel1Collapsed)
            {
                this.splitContainerEx2.Panel1Collapsed = false;
            }
        }

        private void UserCheckReport_Shown(object sender, EventArgs e)
        {
            this.richTextBox1.BackColor = this.BackColor;
            IList<IPatientReport> listResult = PCRRoot.SearchAllReport();
            AddSearchResultToListView(listResult);
        }

        private void UserCheckReport_Resize(object sender, EventArgs e)
        {

        }
    }
}
